package com.aiyige.share;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.im.RecentContactHelper;
import com.aiyige.model.User;
import com.aiyige.model.moment.entity.Moment;
import com.aiyige.share.adapter.ShareContactAdapter;
import com.aiyige.share.adapter.ShareThirdPlatformAdapter;
import com.aiyige.share.model.ShareContactItem;
import com.aiyige.share.model.ShareEntity;
import com.aiyige.share.model.ShareLogRequest;
import com.aiyige.share.model.ShareThirdPlatformItem;
import com.aiyige.share.selectcontact.eventbus.EventSelectShareContactItem;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.ShareUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.widget.BaseBottomDialogFragment;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.vondear.rxtools.RxClipboardTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class ShareDialog extends BaseBottomDialogFragment {
    @BindView(R.id.contactRv)
    RecyclerView contactRv;
    @BindView(R.id.thirdPlatformRv)
    RecyclerView thirdPlatformRv;
    Unbinder unbinder;
    @BindView(R.id.cancelLayout)
    FrameLayout cancelLayout;
    ShareContactAdapter shareContactAdapter;
    ShareThirdPlatformAdapter shareThirdPlatformAdapter;
    List<ShareContactItem> shareContactItemList = new LinkedList<>();
    List<ShareThirdPlatformItem> shareThirdPlatformItemList = new LinkedList<>();
    FragmentActivity fragmentActivity;
    ShareEntity shareEntity;


    public ShareDialog() {
        shareContactItemList = new LinkedList<>();
        try {
            shareContactItemList.addAll(RecentContactHelper.getInstance().getShareContactList(10));
        } catch (Exception e) {

        }
        this.shareContactItemList.add(ShareContactItem.newBuilder()
                .type(ShareContactItem.TYPE_MORE)
                .build());

        shareThirdPlatformItemList = new LinkedList<>();
        shareThirdPlatformItemList.add(ShareThirdPlatformItem.newBuilder()
                .type(ShareThirdPlatformItem.TYPE_WEIXIN)
                .build());
        shareThirdPlatformItemList.add(ShareThirdPlatformItem.newBuilder()
                .type(ShareThirdPlatformItem.TYPE_FRIEND)
                .build());
        shareThirdPlatformItemList.add(ShareThirdPlatformItem.newBuilder()
                .type(ShareThirdPlatformItem.TYPE_QQ)
                .build());
        shareThirdPlatformItemList.add(ShareThirdPlatformItem.newBuilder()
                .type(ShareThirdPlatformItem.TYPE_WEIBO)
                .build());
        shareThirdPlatformItemList.add(ShareThirdPlatformItem.newBuilder()
                .type(ShareThirdPlatformItem.TYPE_LINK)
                .build());
//        shareThirdPlatformItemList.add(ShareThirdPlatformItem.newBuilder()
//                .type(ShareThirdPlatformItem.TYPE_REPORT)
//                .build());
        shareEntity = ShareEntity.newBuilder().build();

    }

    public FragmentActivity getFragmentActivity() {
        return fragmentActivity;
    }

    public void setFragmentActivity(FragmentActivity fragmentActivity) {
        this.fragmentActivity = fragmentActivity;
    }

    public static ShareDialog newInstance(FragmentActivity fragmentActivity) {
        ShareDialog shareDialog = new ShareDialog();
        shareDialog.setFragmentActivity(fragmentActivity);
        return shareDialog;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.share_dialog, container, false);
        unbinder = ButterKnife.bind(this, view);
        shareContactAdapter = new ShareContactAdapter();
        shareThirdPlatformAdapter = new ShareThirdPlatformAdapter();
        contactRv.setLayoutManager(new LinearLayoutManager(view.getContext(), LinearLayoutManager.HORIZONTAL, false));
        thirdPlatformRv.setLayoutManager(new LinearLayoutManager(view.getContext(), LinearLayoutManager.HORIZONTAL, false));
        shareContactAdapter.bindToRecyclerView(contactRv);
        shareThirdPlatformAdapter.bindToRecyclerView(thirdPlatformRv);
        shareContactAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!AccountUtil.isLogin()) {
                    ARouter.getInstance()
                            .build(ARouterConfig.LoginPage)
                            .navigation();
                    dismiss();
                    return;
                }


                ShareContactItem shareContactItem = shareContactAdapter.getItem(position);
                switch (shareContactItem.getType()) {
                    case ShareContactItem.TYPE_MORE:
                        ARouter.getInstance()
                                .build(ARouterConfig.SelectContactPage)
                                .navigation();
                        break;
                    case ShareContactItem.TYPE_NORMAL:
                        shareEntity.setContact(shareContactItem);
                        shareToContact();
                        dismiss();
                        break;
                }

            }
        });
        shareThirdPlatformAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String shareUrl = "";
                String title = "";
                String detail = "";
                String imageUrl = "";
                switch (shareEntity.getShareType()) {
                    case ShareEntity.SHARE_TYPE_MOMENT:
                        shareUrl = StringUtils.escapeEmptyString(shareEntity.getMoment().getWebUrl());
                        title = StringUtils.escapeEmptyString(shareEntity.getMoment().getTitle());
                        detail = StringUtils.escapeEmptyStringWithDefault(shareEntity.getMoment().getSummary(), " ");
                        imageUrl = StringUtils.escapeEmptyString(ListUtil.getFirstItem(shareEntity.getMoment().getCover()));
                        break;

                    case ShareEntity.SHARE_TYPE_USER:
                        shareUrl = StringUtils.escapeEmptyString(shareEntity.getUser().getMoreBackup().getWebUrl());
                        title = StringUtils.escapeEmptyString(shareEntity.getUser().getAccount());
                        detail = StringUtils.escapeEmptyStringWithDefault(shareEntity.getUser().getMoreBackup().getIntroduce(), " ");
                        imageUrl = StringUtils.escapeEmptyString(shareEntity.getUser().getAvatar());
                        break;
                    case ShareEntity.SHARE_TYPE_LINK:
                        shareUrl = StringUtils.escapeEmptyString(shareEntity.getLink());
                        title = "";
                        detail = " ";
                        imageUrl = "";
                        break;
                }
                final ShareThirdPlatformItem shareThirdPlatformItem = shareThirdPlatformAdapter.getItem(position);
                switch (shareThirdPlatformItem.getType()) {
                    case ShareThirdPlatformItem.TYPE_FRIEND:
                    case ShareThirdPlatformItem.TYPE_QQ:
                    case ShareThirdPlatformItem.TYPE_WEIXIN:
                    case ShareThirdPlatformItem.TYPE_WEIBO: {
                        SHARE_MEDIA shareMedia;
                        switch (shareThirdPlatformItem.getType()) {
                            case ShareThirdPlatformItem.TYPE_FRIEND:
                                shareMedia = SHARE_MEDIA.WEIXIN_CIRCLE;
                                if (!ShareUtil.isWeixinAvilible()) {
                                    ToastX.show(R.string.weixin_not_install);
                                    return;
                                }
                                break;
                            case ShareThirdPlatformItem.TYPE_QQ:
                                shareMedia = SHARE_MEDIA.QQ;
                                if (!ShareUtil.isQQClientAvailable()) {
                                    ToastX.show(R.string.qq_not_install);
                                    return;
                                }
                                break;
                            case ShareThirdPlatformItem.TYPE_WEIXIN:
                                shareMedia = SHARE_MEDIA.WEIXIN;
                                if (!ShareUtil.isWeixinAvilible()) {
                                    ToastX.show(R.string.weixin_not_install);
                                    return;
                                }
                                break;
                            case ShareThirdPlatformItem.TYPE_WEIBO:
                                shareMedia = SHARE_MEDIA.SINA;
                                break;
                            default:
                                shareMedia = SHARE_MEDIA.QQ;
                                if (!ShareUtil.isQQClientAvailable()) {
                                    ToastX.show(R.string.qq_not_install);
                                    return;
                                }
                                break;
                        }


                        UMWeb umWeb = new UMWeb(shareUrl);
                        umWeb.setTitle(title);
                        umWeb.setDescription(detail);
                        if (TextUtils.isEmpty(imageUrl)) {
                            umWeb.setThumb(new UMImage(fragmentActivity, R.raw.app_logo_for_share));
                        } else {
                            umWeb.setThumb(new UMImage(fragmentActivity, imageUrl));
                        }
                        new ShareAction(fragmentActivity).setPlatform(shareMedia)
                                .withMedia(umWeb)
                                .setCallback(new UMShareListener() {
                                    @Override
                                    public void onStart(SHARE_MEDIA share_media) {

                                    }

                                    @Override
                                    public void onResult(SHARE_MEDIA share_media) {
                                        if (share_media.name().equals("WEIXIN_FAVORITE")) {
                                            ToastX.show(share_media + " 收藏成功啦");
                                        } else {
                                            if (share_media != SHARE_MEDIA.MORE && share_media != SHARE_MEDIA.SMS
                                                    && share_media != SHARE_MEDIA.EMAIL
                                                    && share_media != SHARE_MEDIA.FLICKR
                                                    && share_media != SHARE_MEDIA.FOURSQUARE
                                                    && share_media != SHARE_MEDIA.TUMBLR
                                                    && share_media != SHARE_MEDIA.POCKET
                                                    && share_media != SHARE_MEDIA.PINTEREST
                                                    && share_media != SHARE_MEDIA.INSTAGRAM
                                                    && share_media != SHARE_MEDIA.GOOGLEPLUS
                                                    && share_media != SHARE_MEDIA.YNOTE
                                                    && share_media != SHARE_MEDIA.EVERNOTE) {
                                            }
                                            try {
                                                ShareLogRequest shareLogRequest = ShareLogRequest.newBuilder()
                                                        .createTime(System.currentTimeMillis())
                                                        .build();
                                                switch (shareEntity.getShareType()) {
                                                    case ShareEntity.SHARE_TYPE_MOMENT: {
                                                        shareLogRequest.setObjectType(ShareLogRequest.OBJECT_TYPE_MOMENT);
                                                        shareLogRequest.setObjectId(shareEntity.getMoment().getId());
                                                        break;
                                                    }
                                                    case ShareEntity.SHARE_TYPE_USER: {
                                                        shareLogRequest.setObjectType(ShareLogRequest.OBJECT_TYPE_USER);
                                                        shareLogRequest.setObjectId(shareEntity.getUser().getId());
                                                        break;
                                                    }
                                                }
                                                switch (shareThirdPlatformItem.getType()) {
                                                    case ShareThirdPlatformItem.TYPE_FRIEND:
                                                        shareLogRequest.setDestination(ShareLogRequest.DESTINATION_WEIXIN_MOMENTS);
                                                        break;
                                                    case ShareThirdPlatformItem.TYPE_QQ:
                                                        shareLogRequest.setDestination(ShareLogRequest.DESTINATION_QQ);
                                                        break;
                                                    case ShareThirdPlatformItem.TYPE_WEIXIN:
                                                        shareLogRequest.setDestination(ShareLogRequest.DESTINATION_WEIXIN);
                                                        break;

                                                    case ShareThirdPlatformItem.TYPE_WEIBO:
                                                        shareLogRequest.setDestination(ShareLogRequest.DESTINATION_WEIBO);
                                                        break;
                                                }
                                                ApiManager.getService().shareLog(shareLogRequest).enqueue(ApiManager.NOOP_CALLBACK);
                                            } catch (Exception e) {
                                            }
                                        }
                                    }

                                    @Override
                                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                        if (share_media != SHARE_MEDIA.MORE && share_media != SHARE_MEDIA.SMS
                                                && share_media != SHARE_MEDIA.EMAIL
                                                && share_media != SHARE_MEDIA.FLICKR
                                                && share_media != SHARE_MEDIA.FOURSQUARE
                                                && share_media != SHARE_MEDIA.TUMBLR
                                                && share_media != SHARE_MEDIA.POCKET
                                                && share_media != SHARE_MEDIA.PINTEREST
                                                && share_media != SHARE_MEDIA.INSTAGRAM
                                                && share_media != SHARE_MEDIA.GOOGLEPLUS
                                                && share_media != SHARE_MEDIA.YNOTE
                                                && share_media != SHARE_MEDIA.EVERNOTE) {
                                        }
                                    }

                                    @Override
                                    public void onCancel(SHARE_MEDIA share_media) {

                                    }
                                })
                                .share();
                        break;
                    }
                    case ShareThirdPlatformItem.TYPE_LINK: {
                        RxClipboardTool.copyText(fragmentActivity, shareUrl);
                        ToastX.show(R.string.have_copy_link);
                        break;
                    }
                    case ShareThirdPlatformItem.TYPE_REPORT: {

                        break;
                    }
                }
                dismiss();
            }
        });
        shareContactAdapter.setNewData(shareContactItemList);
        shareThirdPlatformAdapter.setNewData(shareThirdPlatformItemList);
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(EventSelectShareContactItem event) {
        EventBus.getDefault().removeStickyEvent(event);
        shareEntity.setContact(event.getShareContactItem());
        shareToContact();
        dismiss();
    }

    @Override
    public void onResume() {
        super.onResume();
        registerEventBus();
    }

    @Override
    public void onPause() {
        unregisterEventBus();
        super.onPause();
    }

    public void registerEventBus() {
        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {

        }
    }

    public void unregisterEventBus() {
        try {
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {

        }
    }

    @Override
    public void onDestroyView() {
        unregisterEventBus();
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.cancelLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cancelLayout:
                dismiss();
                break;
        }
    }


    public void shareMoment(Moment moment) {
        shareEntity.setShareType(ShareEntity.SHARE_TYPE_MOMENT);
        shareEntity.setMoment(moment);
        show(fragmentActivity.getSupportFragmentManager(), "");
    }

    public void shareUser(User user) {
        shareEntity.setShareType(ShareEntity.SHARE_TYPE_USER);
        shareEntity.setUser(user);
        show(fragmentActivity.getSupportFragmentManager(), "");
    }

    public void shareLink(String link) {
        shareEntity.setShareType(ShareEntity.SHARE_TYPE_LINK);
        shareEntity.setLink(link);
        show(fragmentActivity.getSupportFragmentManager(), "");
    }


    private void shareToContact() {
        ShareToContactDialog shareToContactDialog = ShareToContactDialog.newInstance(shareEntity);
        shareToContactDialog.show(fragmentActivity.getSupportFragmentManager(), "");
    }
}
